/*
  控件随手指移动改变位置
 */

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'DragApp',
      home: Scaffold(
        appBar: AppBar(title: Text('DragApp'),),
        body: DragWidget(),
      ),
    );
  }
}

class DragWidget extends StatefulWidget {
  @override
  _DragWidgetState createState() => _DragWidgetState();
}

class _DragWidgetState extends State<DragWidget> {

  // 组件宽高
  static const double _widgetWidth = 100;
  static const double _widgetHeight = 100;

  // 全局Key
  GlobalKey _key = GlobalKey();

  // 屏幕宽高
  double stackWidth = 0.0;
  double stackHeight = 0.0;

  // 位置，左边距和上边距
  double _left = 0;
  double _top = 0;

  @override
  void initState() {
    super.initState();
    // 注册一个回调函数，在第一帧渲染开始时回调
    // 获取宽高，这里获取的宽高会报错
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      stackWidth = _key.currentContext!.size!.width;
      stackHeight = _key.currentContext!.size!.height;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanUpdate: (DragUpdateDetails details){
        setState(() { // 更新组件，重新调用build
          print("stackWidth=$stackWidth\nstackHeight=$stackHeight");

          _left += details.delta.dx;
          _top += details.delta.dy;

          // 右边判定
          // if (_left + _widgetWidth > stackWidth) {
          //   _left = stackWidth - _widgetWidth;
          // } else {
          //   _left += details.delta.dx;  // x轴偏移量
          // }
          // // 下边判定
          // if (_top + _widgetHeight > stackHeight) {
          //   _top = stackHeight - _widgetHeight;
          // } else {
          //   _top += details.delta.dy;   // y轴偏移量
          // }
          // // 左边判定
          // if (_left < 0) {
          //   _left = 0;
          // }
          // // 上边判定
          // if (_top < 0) {
          //   _top = 0;
          // }

        });
      },
      child: Stack(
        children: [
          Positioned(
              child: Container(
              color: Colors.amber[100],),
              width: _widgetWidth,
              height: _widgetHeight,
              left: _left,
              top: _top,)
        ],
      ),
    );
  }


}

